﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Senparc.CO2NET.Extensions;
using System.Security.Claims;
using IdentityModel;
using Microsoft.AspNetCore.Authentication.Cookies;
using Music.Utility.Authorization;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authentication;
using Music.Models;
using Music.API.Data;
using System.Transactions;

namespace Music.API.Controllers
{
    /// <summary>
    /// 会员类，定义了CURD相关操作
    /// </summary>
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiExplorerSettings(GroupName = "V1")]
    [ApiController]
    public class MembersController : BaseController<MembersController>
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// MembersController
        /// </summary>
        public MembersController(MusicApiContext context, IHttpContextAccessor httpContextAccessor) : base(context, httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 分页显示会员数据
        /// </summary>
        /// <param name="page">分页</param>
        /// <param name="limit">每页显示数量</param>
        /// <returns></returns>
        [HttpGet]
        [Route("/api/members")]
        public async Task<IActionResult> GetByPage(int page, int limit)
        {
            try
            {
                //DbContextOptionsBuilder<MusicApiContext> dbContextOptionBuilder = new DbContextOptionsBuilder<MusicApiContext>();
                //var connect = new MusicApiContext(dbContextOptionBuilder.UseMySql("Server=127.0.0.1; Database=music_vue3; Uid=root; Pwd=53344521; CharSet=utf8").Options);

                var result = from item in _context.music_members

                             select new
                             {
                                 item.member_id,
                                 item.lang_id,
                                 item.open_id,
                                 item.member_account,
                                 item.mobile_phone,
                                 item.member_password,
                                 item.member_name,
                                 item.real_name,
                                 item.member_avatar,
                                 item.member_gender,
                                 item.member_birth,
                                 item.invite_id,
                                 item.member_qrcode,
                                 item.source_id,
                                 item.medium_id,
                                 item.member_remark,
                                 item.member_status,
                                 item.member_type,
                                 item.created_at,
                                 format_time = item.created_at.ToString("yyyy-MM-dd HH:mm"),

                                 //a.lang_name,
                                 //b.source_name,
                                 //c.medium_name,
                                 //d.type_name,

                             };
                //if (!string.IsNullOrEmpty(search_key))
                //result = result.Where(n => n.search_key.Contains(search_key));
                var list = await result.OrderByDescending(n => n.member_id).Skip((page - 1) * limit).Take(limit).ToListAsync();
                var lCount = result.LongCount();
                if (lCount <= 0)
                {
                    return Json(new { code = 0, msg = "暂无数据" });
                }
                else
                {
                    return Json(new { code = 0, msg = "success", data = list, pageSize = limit, pageNo = page, totalCount = lCount, totalPage = lCount / limit });
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + " -> GetDataByPage");
                return Json(new { code = 1, msg = "error" });
            }
        }

        /// <summary>
        /// 新增会员
        /// </summary>
        /// <param name="members">构造会员对象数据</param>
        /// <returns>返回新增的会员</returns>          
        [HttpPost]
        [Route("/api/members")]
        public async Task<IActionResult> Create(Members members)
        {
            //开启DbContextTransaction事务
            var transaction = _context.Database.BeginTransaction();
            try
            {
                members.member_id = 3;
                members.created_at = DateTime.Now;
                _context.music_members.Add(members);
                await _context.SaveChangesAsync();
                //事务提交
                transaction.Commit();

                return Json(new { code = 0, msg = "添加成功" });
            }
            catch (Exception ex)
            {
                //事务回滚
                transaction.Rollback();
                log.Fatal(ex, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + " -> Create");
                return Json(new { code = 1, msg = ex.Message });
            }
            finally
            {
                //事务销毁
                transaction.Dispose();
            }

        }

        /// <summary>
        /// 删除会员
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>返回是否删除成功</returns>
        [HttpPost]
        [Route("/api/members/del/{id}")]
        public async Task<IActionResult> Delete(long id)
        {
            //创建环境事务(TransactionScope)事务
            var scope = new TransactionScope();
            try
            {
                var item = _context.music_members.Find(id);
                _context.music_members.Remove(item);
                await _context.SaveChangesAsync();
                //事务提交
                scope.Complete();

                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                //事务回滚
                Transaction.Current.Rollback();
                log.Fatal(ex, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + " -> Create");
                return Json(new { code = 1, msg = "error" });
            }
            finally
            {
                //事务销毁
                scope.Dispose();
            }
        }
    }
}
